import pickle
import time
from tkinter import messagebox

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def test_category():
    # 设置浏览器选项
    options = webdriver.ChromeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_argument("disable-blink-features=AutomationControlled")
    options.add_argument(
        'User-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36')

    # 初始化浏览器
    driver = webdriver.Chrome(options=options)
    # 打开网站
    driver.get("https://www.kongfz.com")
    # 加载并添加cookie
    with open('../cookies.pkl', 'rb') as f:
        cookies = pickle.load(f)
        for cookie in cookies:
            if 'sameSite' in cookie:
                del cookie['sameSite']
            driver.add_cookie(cookie)
    # 刷新页面以应用cookie
    driver.refresh()
    time.sleep(2)

    # 等待页面加载
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "a")))

    # 定位并点击 别的 链接
    link = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//a[text()='外文古旧书' and @href='https://book.kongfz.com/Cwaiwenshu/']"))
    )
    link.click()

    # 等待搜索结果加载
    time.sleep(3)
    messagebox.showinfo('分类测试', '分类测试成功')
    # 关闭浏览器
    driver.quit()
